<template>
  <div class="role-management">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" class="animated-button" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <el-table :data="roleList" border class="animated-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="权限" min-width="300">
          <template #default="{ row }">
            <el-tag 
              v-for="perm in formatPermissions(row.permissions)"
              :key="perm"
              class="permission-tag"
              type="info"
            >
              {{ perm }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '新增角色' : '编辑角色'"
      width="600px"
      class="animated-dialog"
    >
      <el-form
        ref="formRef"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="权限" prop="permissions">
          <el-tree
            ref="treeRef"
            :data="permissionTree"
            show-checkbox
            node-key="code"
            :props="{ label: 'name', children: 'children' }"
            :default-checked-keys="roleForm.permissions"
            @check="handlePermissionCheck"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, TreeInstance } from 'element-plus'
import { getRoles, addRole, updateRole, deleteRole, getPermissions } from '@/api/user'
import type { Role, Permission } from '@/api/user'

const loading = ref(false)
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const treeRef = ref<TreeInstance>()
const roleList = ref<Role[]>([])
const permissionTree = ref<Permission[]>([])

// 初始化表单数据
const initRoleForm = (): Role => ({
  name: '',
  description: '',
  permissions: []
})

const roleForm = reactive<Role>(initRoleForm())

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
}

// 格式化权限显示
const formatPermissions = (permissions: string[]) => {
  return permissions.map(code => {
    const findPermName = (perms: Permission[]): string => {
      for (const perm of perms) {
        if (perm.code === code) return perm.name
        if (perm.children) {
          const name = findPermName(perm.children)
          if (name) return name
        }
      }
      return code
    }
    return findPermName(permissionTree.value)
  })
}

// 处理权限选择
const handlePermissionCheck = (node: any, { checkedKeys }: any) => {
  roleForm.permissions = checkedKeys
}

// 加载权限树
const loadPermissions = async () => {
  try {
    const res = await getPermissions()
    if (res.code === 200) {
      permissionTree.value = res.data
    }
  } catch (error) {
    console.error('Load permissions error:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(roleForm, initRoleForm())
}

// 加载角色列表
const loadRoles = async () => {
  try {
    loading.value = true
    const res = await getRoles()
    if (res.code === 200) {
      roleList.value = res.data
    } else {
      ElMessage.error(res.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('Load roles error:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 新增角色
const handleAdd = () => {
  formType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row: Role) => {
  formType.value = 'edit'
  Object.assign(roleForm, row)
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row: Role) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      type: 'warning'
    })
    if (row.id) {
      const res = await deleteRole(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadRoles()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }
  } catch {
    // 取消删除
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (formType.value === 'add') {
          const res = await addRole(roleForm)
          if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisible.value = false
            loadRoles()
          } else {
            ElMessage.error(res.message || '添加失败')
          }
        } else {
          const res = await updateRole(roleForm)
          if (res.code === 200) {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            loadRoles()
          } else {
            ElMessage.error(res.message || '修改失败')
          }
        }
      } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error(formType.value === 'add' ? '添加失败' : '修改失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(async () => {
  await loadPermissions()
  loadRoles()
})
</script>

<style lang="less" scoped>
.role-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.permission-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

// 复用动画样式
.animated-table {
  .el-table__row {
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateX(5px);
      background-color: #f5f7fa !important;
    }
  }
}

.animated-button {
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.animated-dialog {
  :deep(.el-dialog) {
    transform: scale(0.8);
    opacity: 0;
    transition: all 0.3s ease-out;
    
    &.dialog-fade-enter-active {
      transform: scale(1);
      opacity: 1;
    }
  }
  
  :deep(.el-form-item) {
    opacity: 0;
    transform: translateY(20px);
    animation: slideUp 0.3s ease forwards;
    
    &:nth-child(1) { animation-delay: 0s; }
    &:nth-child(2) { animation-delay: 0.1s; }
    &:nth-child(3) { animation-delay: 0.2s; }
  }
}

@keyframes slideUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style> 